﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using Common;
using Taobao.Top.Api;
using Taobao.Top.Api.Request;
using Taobao.Top.Api.Domain;
using System.Net;
using System.Text;
using System.IO;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using System.Xml;

public partial class top_crm_grouplist : System.Web.UI.Page
{
    public string session = string.Empty;
    public string nick = string.Empty;
    public string id = string.Empty;
    public string now = string.Empty;
    public string totalcustomer = string.Empty;
    public string act = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        id = utils.NewRequest("id", utils.RequestType.QueryString);
        string act = utils.NewRequest("act", utils.RequestType.QueryString);
        Common.Cookie cookie = new Common.Cookie();
        string taobaoNick = cookie.getCookie("nick");
        session = cookie.getCookie("top_sessiongroupbuy");
        string iscrm = cookie.getCookie("iscrm");
        Rijndael_ encode = new Rijndael_("tetesoft");
        nick = encode.Decrypt(taobaoNick);

        //过期判断
        if (string.IsNullOrEmpty(taobaoNick))
        {
            string msg = "尊敬的淘宝卖家，非常抱歉的告诉您，您还没有购买此服务或者登录信息已失效，如需继续使用请<a href='http://fuwu.taobao.com/serv/detail.htm?service_id=4545' target='_blank'>进入该服务</a>，谢谢！";
            Response.Redirect("buy.aspx?msg=" + HttpUtility.UrlEncode(msg));
            Response.End();
            return;
        }


        //过期判断
        if (!IsBuy(nick))
        {
            string msg = "尊敬的" + nick + "，非常抱歉的告诉您，只有VIP版本才能使用【客户关系营销】功能，如需继续使用请<a href='http://fuwu.taobao.com/ser/detail.htm?service_code=service-0-22904&frm=haoping' target='_blank'>购买高级会员服务</a>，谢谢！";
            Response.Redirect("buy.aspx?msg=" + HttpUtility.UrlEncode(msg));
            Response.End();
            return;
        }

        if (!IsPostBack)
        {
            if (act == "update")
            {
                UpdateData();
            }
            else if (act == "del")
            {
                DeleteData();
            }
            else
            {
                BindData();
            }
        }
    }

    /// <summary>
    /// 删除数据
    /// </summary>
    private void DeleteData()
    {
        //sql = "UPDATE TCS_Customer SET groupguid = '' WHERE nick = '" + nick + "' AND groupguid = '" + id + "'";
        //utils.ExecuteNonQuery(sql);

        //通过接口删除会员分组
        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";
        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("group_id", id);
        string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.group.delete", session, param);

        //删除本地数据库
        string sql = "UPDATE TCS_Group SET isdel = 1 WHERE nick = '" + nick + "' AND guid = '" + id + "'";
        utils.ExecuteNonQuery(sql);

        Response.Write("<script>alert('删除成功！');window.location.href='grouplist.aspx';</script>");
        Response.End();
    }

    /// <summary>
    /// 更新数据
    /// </summary>
    private void UpdateData()
    {
        string id = utils.NewRequest("id", utils.RequestType.QueryString);
        string sql = "SELECT * FROM TCS_Group WHERE nick = '" + nick + "' AND isdel = 0 AND guid = '" + id + "'";
        //Response.Write(sql);
        string condition = string.Empty;
        DataTable dt = utils.ExecuteDataTable(sql);
        if (dt.Rows.Count > 0)
        {
            string price = dt.Rows[0]["price"].ToString();
            string priceend = dt.Rows[0]["priceend"].ToString();
            string area = dt.Rows[0]["arealist"].ToString();
            string actdate = dt.Rows[0]["actdate"].ToString();
            string actdateend = dt.Rows[0]["actdateend"].ToString();
            string groupid = dt.Rows[0]["taobaoid"].ToString();

            string name = utils.NewRequest("name", utils.RequestType.Form);
            string str = string.Empty;

            string left = string.Empty;
            string right = string.Empty;
            string result = string.Empty;

            //同时创建CRM里面的分组
            string appkey = "12159997";
            string secret = "614e40bfdb96e9063031d1a9e56fbed5";
            IDictionary<string, string> param = new Dictionary<string, string>();

            string[] areaList = area.Split(',');
            for (int k = 0; k < areaList.Length; k++)
            {
                for (int i = 1; i < 9999; i++)
                {
                    //获取买家分组信息
                    param = new Dictionary<string, string>();
                    param.Add("page_size", "100");
                    param.Add("current_page", i.ToString());
                    param.Add("relation_source", "1");
                    param.Add("order", "lastest_time");
                    param.Add("sort", "desc");
                    //会员检索条件
                    if (price.Length != 0)
                    {
                        param.Add("min_trade_amount", price);
                    }
                    if (priceend.Length != 0)
                    {
                        param.Add("max_trade_amount", priceend);
                    }
                    if (area.Length != 0)
                    {
                        param.Add("province", areaList[k]);
                    }
                    if (actdate.Length != 0)
                    {
                        param.Add("min_last_trade_time", DateTime.Parse(actdate).ToString("yyyy-MM-dd HH:mm:ss"));
                    }
                    if (actdateend.Length != 0)
                    {
                        param.Add("max_last_trade_time", DateTime.Parse(actdateend).ToString("yyyy-MM-dd HH:mm:ss"));
                    }

                    result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.members.search", session, param);
                    Regex reg = new Regex(@"<crm_member>([\s\S]*?)</crm_member>", RegexOptions.IgnoreCase);
                    MatchCollection match = reg.Matches(result);

                    //如果没有了则退出
                    if (match.Count == 0)
                    {
                        break;
                    }
                    //循环更新
                    for (int j = 0; j < match.Count; j++)
                    {
                        string strCus = match[j].Groups[0].ToString();
                        string buyer_nick = GetValueByProperty(strCus, "buyer_nick");
                        string group_ids = GetValueByProperty(strCus, "group_ids");

                        //更新买家会员分组
                        param = new Dictionary<string, string>();
                        param.Add("buyer_nick", buyer_nick);
                        param.Add("status", "normal");
                        param.Add("group_ids", InitGroupId(group_ids,groupid));

                        result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.memberinfo.update", session, param);
                        //Response.Write(group_ids + "|" + groupid + "<br>");
                    }
                }
            }
        }

        Response.Write("<script>alert('会员组会员更新成功！');window.location.href='grouplist.aspx';</script>");
        Response.End();
    }

    private string InitGroupId(string group_ids, string groupid)
    {
        if (group_ids.IndexOf(groupid) != -1)
        {
            return group_ids;
        }
        else
        {
            return group_ids + "|" + groupid;
        }
    }

    private void BindData()
    {
        string sql = "SELECT * FROM TCS_Group WHERE 1 = 2";
        DataTable dtTaobao = utils.ExecuteDataTable(sql);

        sql = "SELECT * FROM TCS_Group WHERE nick = '" + nick + "' AND isdel = 0";
        DataTable dt = utils.ExecuteDataTable(sql);

        string appkey = "12159997";
        string secret = "614e40bfdb96e9063031d1a9e56fbed5";

        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("page_size", "100");
        param.Add("current_page", "1");

        string result = Post("http://gw.api.taobao.com/router/rest", appkey, secret, "taobao.crm.groups.get", session, param);
        Regex reg = new Regex(@"<group>([\s\S]*?)</group>", RegexOptions.IgnoreCase);
        MatchCollection match = reg.Matches(result);

        for (int i = 0; i < match.Count; i++)
        {
            string str = match[i].Groups[0].ToString();
            string groupid = GetValueByProperty(str, "group_id");
            DataRow row = dtTaobao.NewRow();

            //绑定显示数据
            row["name"] = GetValueByProperty(str, "group_name");
            row["count"] = GetValueByProperty(str, "member_count");
            row["nick"] = "非本服务创建分组，不可操作";

            //如果数据库内有记录则显示
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                if (groupid == dt.Rows[j]["taobaoid"].ToString())
                {
                    row["price"] = dt.Rows[j]["price"];
                    row["priceend"] = dt.Rows[j]["priceend"];
                    row["arealist"] = InitAreaStr(dt.Rows[j]["arealist"].ToString());
                    row["actdate"] = dt.Rows[j]["actdate"];
                    row["actdateend"] = dt.Rows[j]["actdateend"];
                    row["nick"] = "<a href='grouplist.aspx?act=update&id=" + dt.Rows[j]["guid"].ToString() + "' onclick=\"return confirm('当您会员较多的时候此操作可能会执行很长时间，您确定吗？')\">更新会员数据</a> | <a href='grouplist.aspx?act=del&id=" + groupid + "' onclick=\"return confirm('您确定要删除吗，该操作不可恢复？')\">删除</a>";

                    dtTaobao.Rows.Add(row);
                }
            }
        }

        rptArticle.DataSource = dtTaobao;
        rptArticle.DataBind();
    }

    private string InitAreaStr(string list)
    {
        string str = string.Empty;
        if (list == "")
            return "";

        IDictionary<string, string> paramSheng = InitShengInfo();

        string[] ary = list.Split(',');

        for (int i = 0; i < ary.Length; i++)
        {
            if (i == 0)
            {
                str += paramSheng[ary[i]];
            }
            else
            {
                str += "|" + paramSheng[ary[i]];
            }
        }

        return str;
    }

    private IDictionary<string, string> InitShengInfo()
    {
        IDictionary<string, string> param = new Dictionary<string, string>();
        param.Add("0", "其他");
        param.Add("1", "北京");
        param.Add("2", "天津");
        param.Add("3", "河北省");
        param.Add("4", "山西省");
        param.Add("5", "内蒙古自治区");
        param.Add("6", "辽宁省");
        param.Add("7", "吉林省");
        param.Add("8", "黑龙江省");
        param.Add("9", "上海");
        param.Add("10", "江苏省");
        param.Add("11", "浙江省");
        param.Add("12", "安徽省");
        param.Add("13", "福建省");
        param.Add("14", "江西省");
        param.Add("15", "山东省");
        param.Add("16", "河南省");
        param.Add("17", "湖北省");
        param.Add("18", "湖南省");
        param.Add("19", "广东省");
        param.Add("20", "广西壮族自治区");
        param.Add("21", "海南省");
        param.Add("22", "重庆");
        param.Add("23", "四川省");
        param.Add("24", "贵州省");
        param.Add("25", "云南省");
        param.Add("26", "西藏自治区");
        param.Add("27", "陕西省");
        param.Add("28", "甘肃省");
        param.Add("29", "青海省");
        param.Add("30", "宁夏回族自治区");
        param.Add("31", "新疆维吾尔自治区");
        param.Add("32", "台湾省");
        param.Add("33", "香港特别行政区");
        param.Add("34", "澳门特别行政区");
        param.Add("35", "海外");
        param.Add("36", "其他");

        return param;
    }

    public static string GetValueByProperty(string str, string prop)
    {
        Regex reg = new Regex(@"<" + prop + @">([^<]*)</" + prop + @">", RegexOptions.IgnoreCase);
        if (reg.IsMatch(str))
        {
            return reg.Match(str).Groups[1].ToString();
        }
        else
        {
            return "";
        }
    }

    /// <summary>
    /// 判断该用户是否订购了该服务
    /// </summary>
    /// <param name="nick"></param>
    /// <returns></returns>
    private bool IsBuy(string nick)
    {
        string sql = "SELECT plus FROM TCS_ShopSession WHERE nick = '" + nick + "'";
        DataTable dt = utils.ExecuteDataTable(sql);
        if (dt.Rows.Count != 0)
        {
            string plus = dt.Rows[0][0].ToString();
            if (plus.IndexOf("crm") != -1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }


    #region TOP API
    /// <summary> 
    /// 给TOP请求签名 API v2.0 
    /// </summary> 
    /// <param name="parameters">所有字符型的TOP请求参数</param> 
    /// <param name="secret">签名密钥</param> 
    /// <returns>签名</returns> 
    protected static string CreateSign(IDictionary<string, string> parameters, string secret)
    {
        parameters.Remove("sign");
        IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
        IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();
        StringBuilder query = new StringBuilder(secret);
        while (dem.MoveNext())
        {
            string key = dem.Current.Key;
            string value = dem.Current.Value;
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
            {
                query.Append(key).Append(value);
            }
        }
        query.Append(secret);
        MD5 md5 = MD5.Create();
        byte[] bytes = md5.ComputeHash(Encoding.UTF8.GetBytes(query.ToString()));
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < bytes.Length; i++)
        {
            string hex = bytes[i].ToString("X");
            if (hex.Length == 1)
            {
                result.Append("0");
            }
            result.Append(hex);
        }
        return result.ToString();
    }
    /// <summary> 
    /// 组装普通文本请求参数。 
    /// </summary> 
    /// <param name="parameters">Key-Value形式请求参数字典</param> 
    /// <returns>URL编码后的请求数据</returns> 
    protected static string PostData(IDictionary<string, string> parameters)
    {
        StringBuilder postData = new StringBuilder();
        bool hasParam = false;
        IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
        while (dem.MoveNext())
        {
            string name = dem.Current.Key;
            string value = dem.Current.Value;
            // 忽略参数名或参数值为空的参数 
            if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
            {
                if (hasParam)
                {
                    postData.Append("&");
                }
                postData.Append(name);
                postData.Append("=");
                postData.Append(Uri.EscapeDataString(value));
                hasParam = true;
            }
        }
        return postData.ToString();
    }
    /// <summary> 
    /// TOP API POST 请求 
    /// </summary> 
    /// <param name="url">请求容器URL</param> 
    /// <param name="appkey">AppKey</param> 
    /// <param name="appSecret">AppSecret</param> 
    /// <param name="method">API接口方法名</param> 
    /// <param name="session">调用私有的sessionkey</param> 
    /// <param name="param">请求参数</param> 
    /// <returns>返回字符串</returns> 
    public static string Post(string url, string appkey, string appSecret, string method, string session,
    IDictionary<string, string> param)
    {
        #region -----API系统参数----
        param.Add("app_key", appkey);
        param.Add("method", method);
        param.Add("session", session);
        param.Add("timestamp", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
        param.Add("format", "xml");
        param.Add("v", "2.0");
        param.Add("sign_method", "md5");
        param.Add("sign", CreateSign(param, appSecret));
        #endregion
        string result = string.Empty;
        #region ---- 完成 HTTP POST 请求----
        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        req.Method = "POST";
        req.KeepAlive = true;
        req.Timeout = 300000;
        req.ContentType = "application/x-www-form-urlencoded;charset=gb2312";
        byte[] postData = Encoding.UTF8.GetBytes(PostData(param));
        Stream reqStream = req.GetRequestStream();
        reqStream.Write(postData, 0, postData.Length);
        reqStream.Close();
        HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
        Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);
        Stream stream = null;
        StreamReader reader = null;
        stream = rsp.GetResponseStream();
        reader = new StreamReader(stream, encoding);
        result = reader.ReadToEnd();
        if (reader != null) reader.Close();
        if (stream != null) stream.Close();
        if (rsp != null) rsp.Close();
        #endregion
        return Regex.Replace(result, @"[\x00-\x08\x0b-\x0c\x0e-\x1f]", "");
    }
    #endregion
}